package com.ldk.admin.controller;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.*;
import com.ldk.framework.service.IAreaService;
import com.ldk.framework.service.ICompanypermitService;
import com.ldk.framework.service.ITicketLevelService;
import com.ldk.framework.service.ITicketRelateService;
import com.ldk.framework.service.ITicketUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * A.4.5、网约车平台公司经营许可信息
 *
 * @author xiangwl
 * 2018年8月9日
 * com.ldk.admin.controller
 * CompanypermitController
 */
@Controller
@RequestMapping("/ticketuser")
public class TicketSaleController extends BaseController {
    /**
     * 路由地址
     */
    private final String route = "ticketuser";
    /**
     * 模块名称
     */
    private final String module = "票务经理";

    @Autowired
    private ITicketUserService ticketUserService;
    @Autowired
    private ITicketLevelService ticketLevelService;
    @Autowired
    private ITicketRelateService ticketRelateService;

    @RequestMapping("/list")
    public ModelAndView list(ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, "", "", module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add");
        map.addAttribute("route", route);
        map.addAttribute("module", module);

        return new ModelAndView("/ticket/list");
    }

    @RequestMapping("/list1")
    public ModelAndView list1(ModelMap map, HttpServletRequest request,
                              HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, "", "",  "票务经理待审核列表", "/" + route + "/list1", "", "");
        map.addAttribute("route", route);
        map.addAttribute("module", module);

        return new ModelAndView("/ticket/list1");
    }

    @RequestMapping("/list2")
    public ModelAndView list2(ModelMap map, HttpServletRequest request,
                              HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, "", "",   "票务经理审核未通过列表", "/" + route + "/list2", "", "");
        map.addAttribute("route", route);
        map.addAttribute("module", module);

        return new ModelAndView("/ticket/list2");
    }

    @ResponseBody
    @RequestMapping("/getList")
    public LigerUIGridResult<TicketUser> getList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                 @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                                 @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                                 HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        TicketUser query = new TicketUser();
        query.setState(2);
        if (!StringUtils.isBlank(searchKey)) {
            query.setSearchKey(searchKey);
        }
        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<TicketUser> result = ticketUserService.selectPageList("", query, pageable);

        LigerUIGridResult<TicketUser> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        return grid;
    }


    @ResponseBody
    @RequestMapping("/getList1")
    public LigerUIGridResult<TicketUser> getList1(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                  @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                                  @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                                  HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        TicketUser query = new TicketUser();
        query.setState(1);
        if (!StringUtils.isBlank(searchKey)) {
            query.setSearchKey(searchKey);
        }
        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<TicketUser> result = ticketUserService.selectPageList("", query, pageable);

        LigerUIGridResult<TicketUser> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        return grid;
    }

    @ResponseBody
    @RequestMapping("/getList2")
    public LigerUIGridResult<TicketUser> getList2(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                  @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                                  @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                                  HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        TicketUser query = new TicketUser();
        query.setState(4);
        if (!StringUtils.isBlank(searchKey)) {
            query.setSearchKey(searchKey);
        }
        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<TicketUser> result = ticketUserService.selectPageList("", query, pageable);

        LigerUIGridResult<TicketUser> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        return grid;
    }

    @RequestMapping("/add")
    public ModelAndView add(ModelMap map, HttpServletRequest request,
                            HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add", "", "");
        setForm(map, "/" + route + "/insert", null);

        map.addAttribute("module", module);
        setViewMode(map, ViewMode.Add);

        TicketUser model = new TicketUser();
        //动态生成推荐二维码
        String saleNo = ticketUserService.generateSaleNo("");
        model.setSaleNo(saleNo);

        return new ModelAndView("/ticket/info", "model", model);
    }

    @RequestMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        TicketUser query = new TicketUser();
        query.setId(id);

        TicketUser model = ticketUserService.selectOne("", query);
        if (model == null) {
            return new ModelAndView("redirect:/" + route + "/list");
        }
        setLinks(map, module + "管理", "/" + route + "/list", "编辑" + module, "/" + route + "/edit/" + id, "", "");
        setForm(map, "/" + route + "/update", null);
        map.addAttribute("module", module);
        setViewMode(map, ViewMode.Edit);

        return new ModelAndView("/ticket/info", "model", model);
    }

    @RequestMapping("/edit1/{id}")
    public ModelAndView edit1(@PathVariable long id, ModelMap map, HttpServletRequest request,
                              HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        TicketUser query = new TicketUser();
        query.setId(id);

        TicketUser model = ticketUserService.selectOne("", query);
        if (model == null) {
            return new ModelAndView("redirect:/" + route + "/list1");
        }
        setLinks(map,  "票务经理待审核列表", "/" + route + "/list1", "审核" + module, "/" + route + "/edit1/" + id, "", "");
        setForm(map, "/" + route + "/update", null);
        map.addAttribute("module", module);
        setViewMode(map, ViewMode.Edit);

        return new ModelAndView("/ticket/info1", "model", model);
    }

    @RequestMapping("/insert")
    public ModelAndView insert(@ModelAttribute("model") TicketUser model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        try {
            TicketUser query = new TicketUser();
            query.setPhoneNo(model.getPhoneNo());
            long count = ticketUserService.selectCount("", query);
            if (count > 0) {
                rst.AddError(String.format("分销经理:%s已经存在", model.getPhoneNo()));
                return new ModelAndView("redirect:/" + route + "/add");
            }
            model.setCreateTime(SystemUtil.getAllSeconds());
            if (model.getEnabled() == null) {
                model.setEnabled(true);
            }
            model.setBalance(0.0);
            model.setCash(0.0);
            model.setIncome(0.0);
            model.setState(2);
            model.setRecNum(0);

            //查询等级
            TicketLevel query1 = new TicketLevel();
            query1.setLevel(1);
            TicketLevel ticketLevel = ticketLevelService.selectOne("", query1);
            if(ticketLevel!=null){
                model.setLevel(ticketLevel.getLevel());
                model.setLevelName(ticketLevel.getName());
            }else {
                model.setLevel(1);
                model.setLevelName("黄金票务经理");
            }
            //查询我的上级，上上级
            TicketRelate relate = new TicketRelate();
            relate.setPhoneNo(model.getPhoneNo());
            List<TicketRelate> list = ticketRelateService.selectList("", relate);
            if (list != null && list.size() > 0) {
                for (TicketRelate ticketRelate : list) {
                    if(ticketRelate.getLevelType()==1){
                        model.setLevel1Phone(ticketRelate.getLevelPhone());
                        model.setLevel1Name(ticketRelate.getLevelName());
                    }
                    if(ticketRelate.getLevelType()==2){
                        model.setLevel2Phone(ticketRelate.getLevelPhone());
                        model.setLevel1Name(ticketRelate.getLevelName());
                    }
                }
            }
            int row = ticketUserService.insert("", model);

            if (row > 0) {
                rst.AddOk("添加" + module + "成功");
            } else {
                rst.AddError("添加" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("添加" + module + "失败");
            logger.error(e.getMessage());
        }
        return new ModelAndView("redirect:/" + route + "/add");
    }

    @RequestMapping("/update")
    public ModelAndView update(@ModelAttribute("model") TicketUser model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();

        redAttr.addAttribute("id", model.getId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        try {
            TicketUser query = new TicketUser();
            query.setPhoneNo(model.getPhoneNo());
            TicketUser area = ticketUserService.selectOne("", query);
            if (area != null && !area.getId().equals(model.getId())) {
                rst.AddError(String.format("分销经理:%s已经存在", model.getPhoneNo()));
                return new ModelAndView("redirect:/" + route + "/edit/" + model.getId());
            }

            model.setCreateTime(SystemUtil.getAllSeconds());
            if (model.getEnabled() == null) {
                model.setEnabled(true);
            }
            int row = ticketUserService.updateByKey("", model);
            if (row > 0) {
                rst.AddOk("修改" + module + "成功");
            } else {
                rst.AddError("修改" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("修改" + module + "失败");
            logger.error(e.getMessage());
        }

        return new ModelAndView("redirect:/" + route + "/edit/{id}");
    }

    /**
     * 浏览
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/view/{id}")
    public ModelAndView view(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);

        setViewMode(map, ViewMode.View);
        TicketUser query = new TicketUser();
        query.setId(id);
        TicketUser model = ticketUserService.selectOne("", query);

        map.addAttribute("module", module);

        return new ModelAndView("/ticket/info", "model", model);
    }

    @ResponseBody
    @RequestMapping("/remove/{id}")
    public ResponseResult remove(@PathVariable long id, HttpServletRequest request) {

        ResponseResult rst = new ResponseResult();
        if (id < 1) {
            rst.AddError("删除" + module + "错误");
            return rst;
        }
        Boolean successed = false;
        try {
            TicketUser query = new TicketUser();
            query.setId(id);
            int row = ticketUserService.deleteByKey("", query);
            successed = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (successed) {
            rst.AddOk("删除" + module + "成功");
        } else {
            rst.AddError("删除" + module + "失败");
        }

        return rst;
    }

}
